import router from '@/router'
import { getTabRouteByRoute } from '@/stores/tab/helpers'
import { acceptHMRUpdate, defineStore } from 'pinia'
import { useAppStore } from '..'

export const useTabStore = defineStore('tabStore', () => {
  const tabs = ref([])
  const activeTab = ref('')

  const appStore = useAppStore()

  function addTab(route) {
    const t = getTabRouteByRoute(route)

    const index = tabs.value.findIndex(tab => tab.fullPath === t.fullPath)

    if (!~index)
      tabs.value.push(t)
  }

  async function removeTab(fullPath) {
    const name = tabs.value.find(tab => tab.fullPath === fullPath)?.name

    if (!name)
      return

    const isActive = activeTab.value === fullPath
    const updateTabs = tabs.value.filter(tab => tab.fullPath !== fullPath)

    if (!isActive) {
      tabs.value = updateTabs
    }
    else if (isActive && updateTabs.length) {
      const activePath = updateTabs.at(-1).fullPath

      await pushAndSetActiveTab(activePath)
      tabs.value = updateTabs
    }
    else {
      await appStore.reloadPage()
    }
  }

  function setActiveTab(fullPath) {
    activeTab.value = fullPath
  }

  async function pushAndSetActiveTab(path) {
    if (!path)
      path = tabs.value.at(-1).fullPath

    await router.push(path)
    setActiveTab(path)
  }

  async function spliceTab(state, index) {
    const currPath = tabs.value[index].fullPath
    const activeIndex = tabs.value.findIndex(tab => tab.fullPath === activeTab.value)

    switch (state) {
      case 'close':
        await removeTab(currPath)
        break
      case 'close-other':
        tabs.value = tabs.value.filter((_, i) => i === index)

        if (activeIndex !== index)
          await pushAndSetActiveTab()
        break
      case 'close-left-side':
        tabs.value.splice(0, index)

        if (activeIndex < index)
          await pushAndSetActiveTab()
        break
      case 'close-right-side':
        tabs.value.splice(index + 1)

        if (activeIndex > index)
          await pushAndSetActiveTab()
    }
  }

  function initTab(route) {
    addTab(route)

    activeTab.value = route.fullPath
  }

  return {
    tabs,
    activeTab,

    addTab,
    removeTab,
    setActiveTab,
    spliceTab,
    initTab,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useTabStore, import.meta.hot))
